{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e30d832c",
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "from pathlib import Path\n",
    "import torch\n",
    "import yaml\n",
    "from torchmetrics import MetricCollection\n",
    "from omegaconf import OmegaConf as OC\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mpl\n",
    "import numpy as np\n",
    "from pytorch_lightning import seed_everything\n",
    "\n",
    "import maploc\n",
    "from maploc.data import MapillaryDataModule\n",
    "from maploc.data.torch import unbatch_to_device\n",
    "from maploc.module import GenericModule\n",
    "from maploc.models.metrics import Location2DError, AngleError\n",
    "from maploc.evaluation.run import resolve_checkpoint_path\n",
    "from maploc.evaluation.viz import plot_example_single\n",
    "\n",
    "from maploc.models.voting import argmax_xyr, fuse_gps\n",
    "from maploc.osm.viz import Colormap, plot_nodes\n",
    "from maploc.utils.viz_2d import plot_images, features_to_RGB, save_plot, add_text\n",
    "from maploc.utils.viz_localization import likelihood_overlay, plot_pose, plot_dense_rotations, add_circle_inset\n",
    "\n",
    "torch.set_grad_enabled(False);\n",
    "plt.rcParams.update({'figure.max_open_warning': 0})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc8bd313",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "conf = OC.load(Path(maploc.__file__).parent / 'conf/data/mapillary.yaml')\n",
    "conf = OC.merge(conf, OC.create(yaml.full_load(\"\"\"\n",
    "data_dir: \"../datasets/MGL_release\"\n",
    "loading:\n",
    "    val: {batch_size: 1, num_workers: 0}\n",
    "    train: ${.val}\n",
    "add_map_mask: true\n",
    "return_gps: true\n",
    "\"\"\")))\n",
    "OC.resolve(conf)\n",
    "dataset = MapillaryDataModule(conf)\n",
    "dataset.prepare_data()\n",
    "dataset.setup()\n",
    "sampler = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c267ed66",
   "metadata": {},
   "outputs": [],
   "source": [
    "experiment = \"orienternet_mgl.ckpt\"\n",
    "# experiment = \"experiment_name\"  # find the best checkpoint\n",
    "# experiment = \"experiment_name/checkpoint-step=N.ckpt\"  # a given checkpoint\n",
    "path = resolve_checkpoint_path(experiment)\n",
    "print(path)\n",
    "cfg = {'model': {\"num_rotations\": 360, \"apply_map_prior\": True}}\n",
    "model = GenericModule.load_from_checkpoint(\n",
    "    path, strict=True, find_best=not experiment.endswith('.ckpt'), cfg=cfg)\n",
    "model = model.eval().cuda()\n",
    "assert model.cfg.data.resize_image == dataset.cfg.resize_image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48efb4e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_dir = None #Path('outputs_mgl_failures/')\n",
    "if out_dir is not None:\n",
    "    !mkdir -p $out_dir/full\n",
    "\n",
    "seed_everything(25) # best = 25\n",
    "loader = dataset.dataloader(\"val\", shuffle=sampler is None, sampler=sampler)\n",
    "metrics = MetricCollection(model.model.metrics()).to(model.device)\n",
    "metrics[\"xy_gps_error\"] = Location2DError(\"uv_gps\", model.cfg.model.pixel_per_meter)\n",
    "for i, batch in zip(range(10), loader):\n",
    "    pred = data = batch_ = None    \n",
    "    batch_ = model.transfer_batch_to_device(batch, model.device, i)\n",
    "    pred = model(batch_)\n",
    "    pred = {k:v.float() if isinstance(v, torch.HalfTensor) else v for k,v in pred.items()}\n",
    "    pred[\"uv_gps\"] = batch[\"uv_gps\"]\n",
    "    loss = model.model.loss(pred, batch_)\n",
    "    results = metrics(pred, batch_)\n",
    "    results.pop(\"xy_expectation_error\")\n",
    "    for k in list(results):\n",
    "        if \"recall\" in k:\n",
    "            results.pop(k)\n",
    "    print(f'{i} {loss[\"total\"].item():.2f}', {k: round(v.item(), 2) for k, v in results.items()})\n",
    "#     if results[\"xy_max_error\"] < 5:\n",
    "#         continue\n",
    "\n",
    "    pred = unbatch_to_device(pred)\n",
    "    data = unbatch_to_device(batch)\n",
    "    plot_example_single(i, model, pred, data, results, plot_bev=True, out_dir=out_dir, show_gps=True)\n",
    "    \n",
    "    continue\n",
    "    scales_scores = pred['pixel_scales']\n",
    "    log_prob = torch.nn.functional.log_softmax(scales_scores, dim=-1)\n",
    "    scales_exp = torch.sum(log_prob.exp() * torch.arange(scales_scores.shape[-1]), -1)\n",
    "    total_score = torch.logsumexp(scales_scores, -1)\n",
    "    plot_images([log_prob.max(-1).values.exp(), scales_exp, total_score], cmaps='jet')\n",
    "    plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
